<template>
	<div>
		<el-container>
			<el-main>
				<el-container class="parent-body">
					<el-header class="content-header">
						<div><i class="el-icon-search"></i> 筛选查询</div>
						<div>
							<!-- 1. 给vue组件绑定事件时候，必须加上native ，否则会认为监听的是来自Item组件自定义的事件。
              例子：如果使用router-link标签，加上@click事件，绑定的事件会无效因为：router-link的作用是单纯的路由跳转，会阻止click事件，
              你可以试试只用click不用native,事件是不会触发的。此时加上.native，才会触发事件。
              2. 等同于在子组件中：子组件内部处理click事件然后向外发送click事件：$emit("click".fn)-->
							<el-button @click="selectResults"
								>查询结果</el-button
							>
						</div>
					</el-header>
					<el-main class="info-main">
						<!--  :model是v-bind:model的缩写,这种只是将父组件的数据传递到了子组件，并没有实现子组件和父组件数据的双向绑定。当然引用类型除外 -->
						<el-form ref="form" :model="form" label-width="100px">
							<el-form-item class="select-div" label="输入搜索：">
								<el-input
									placeholder="品牌名称/关键词"
									class="input-width"
									v-model="form.name"
								></el-input>
							</el-form-item>
						</el-form>
					</el-main>
				</el-container>
			</el-main>
			<el-footer>
				<el-container class="parent-body" style="font-size: 14px;">
					<el-header class="content-header">
						<div><i class="el-icon-s-unfold"></i> 数据列表</div>
						<div style="float:right">
							<el-button @click="addNewBrand" size="small"
								>添加</el-button
							>
							<el-button @click="generateInitial" size="small"
								>生成品牌首字母</el-button
							>
							<el-select
								v-model="sortValue"
								class="selection-width margin-left"
								size="small"
								placeholder="排列方式"
							>
								<el-option
									v-for="item in options"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								></el-option>
							</el-select>
						</div>
					</el-header>
					<el-main class="info-main padding-style">
						<el-table
							ref="multipleTable"
							:data="tableData"
							tooltip-effect="dark"
							style="width: 100%"
							@selection-change="handleSelectionChange"
							border
						>
							<el-table-column
								type="selection"
								width="55"
							></el-table-column>
							<el-table-column
								prop="id"
								label="编号"
								width="120"
							></el-table-column>
							<el-table-column
								prop="name"
								label="品牌名称"
							></el-table-column>
							<el-table-column
								prop="initial"
								label="品牌首字母"
								width="250"
							></el-table-column>
							<el-table-column
								prop="logo"
								label="LOGO"
								width="100"
							>
								<!-- solt-scope=”scope” -->
								<template scope="scope">
									<img
										:src="scope.row.logo"
										width="40"
										height="40"
										class="head_pic"
									/>
								</template>
							</el-table-column>

							<el-table-column
								prop="name"
								label="相关"
								width="250"
							>
								商品:
								<el-button type="text" @click="Goods"
									>100</el-button
								>评价:
								<el-button type="text" @click="Evaluate"
									>100</el-button
								>
							</el-table-column>
							<el-table-column
								prop="delState"
								label="目前状态"
								width="120"
							>
								<template scope="scope">
									<span>{{
										scope.row.delState | delStateFilter
									}}</span>
								</template>
							</el-table-column>
							<el-table-column label="操作" width="200">
								<template slot-scope="scope">
									<el-button
										@click="handleClick(scope.row)"
										size="mini"
										>编辑</el-button
									>
									<el-button
										@click="deleteClick(scope.row.id)"
										v-show="scope.row.delState == '0'"
										size="mini"
										>删除</el-button
									>
								</template>
							</el-table-column>
						</el-table>
					</el-main>

					<el-footer class="footer-style">
						<div class="batch">
							<!-- <el-checkbox  @change="toggleSelectionCheckbox" v-model="checkbox">全选</el-checkbox> -->
							<el-button @click="toggleSelection" size="small"
								>全选</el-button
							>
							<el-select
								v-model="form.type"
								placeholder="批量操作"
								size="small"
								class="selection-width margin-left"
							>
								<el-option label="还原" value="0"></el-option>
								<el-option label="删除" value="1"></el-option>
							</el-select>
							<el-button
								class="margin-left"
								@click="handleSelection"
								size="small"
								>确定</el-button
							>
						</div>
						<div class="pagination">
							<el-pagination
								@size-change="handleSizeChange"
								@current-change="handleCurrentChange"
								:current-page="pageNum"
								:page-sizes="pageSizes"
								:page-size="pageSize"
								layout="total, sizes, prev, pager, next, jumper"
								:total="total"
							></el-pagination>
						</div>
					</el-footer>
				</el-container>
			</el-footer>
		</el-container>

		<el-dialog :title="editTitle" :visible.sync="dialogFormVisible">
			<el-form
				:model="brand"
				:rules="rules"
				label-width="120px"
				ref="brandForm"
			>
				<el-form-item label="品牌名称" prop="name">
					<el-input
						v-model="brand.name"
						style="width: 200px;"
					></el-input>
				</el-form-item>
				<el-form-item label="品牌首字母">
					<el-input
						v-model="brand.initial"
						style="width: 200px;"
					></el-input>
				</el-form-item>
				<el-form-item label="名片LOGO" prop="logo">
					<el-upload
						class="avatar-uploader"
						ref="upload"
						:action="uploadUrl"
						:data="brand"
						:show-file-list="false"
						:on-change="handleChange"
						:on-success="handleUpload"
						:before-upload="beforeUpload"
						:disabled="brand.name.trim() == ''"
						:auto-upload="false"
					>
						<img
							v-if="brand.logo"
							:src="brand.logo"
							class="avatar"
						/>
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
						<div class="el-upload__tip" slot="tip">
							只能上传jpg/png文件，且不超过500kb
						</div>
					</el-upload>
					<!-- <el-upload
              class="upload-demo"
              :data="brand"
              drag
              :action="uploadUrl"
              :on-success="handleUploaded"
              auto-upload
            >
               /*<i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或
                <em>点击上传</em>
              </div> */
              <p style="font-size:14px;margin:0px 10px 0px 10px">
                <span style="font-family:'FontAwesome';font-weight:400;font-size:16px;"></span>
                <span style="font-family:'微软雅黑';font-weight:400;">选择上传文件</span>
              </p>
              <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>-->
				</el-form-item>
			</el-form>
            <!-- 过滤器一般用于一些常见的文本格式化，所以此处不能使用过滤器 -->
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogFormVisible = false">取 消</el-button>
				<el-button
					type="primary"
					@click="brand.id ? insertSave() : updateSave()"
					>确 定</el-button
				>
			</div>
		</el-dialog>
	</div>
</template>
<script>
import brandApi from '@/api/goods/brand'
import request from '@/utils/request'

// 删除状态类型数组  注：必须定义为全局对象
const delStateType = [
	{
		type: 0,
		title: '正常',
	},
	{
		type: 1,
		title: '已删',
	},
]
export default {
	data() {
		return {
			dialogFormVisible: false,
			options: [
				{
					value: 0,
					label: '品牌编号',
				},
				{
					value: 1,
					label: '品牌名称',
				},
				{
					value: 2,
					label: '品牌首字母',
				},
			],
			form: {
				name: '',
				type: null,
				brand: '',
			},
			rules: {
				name: [
					{
						required: true,
						message: '请输入品牌名称',
						trigger: 'blur',
					},
				],
				logo: [
					{
						required: true,
						message: '请选择品牌Logo',
						trigger: 'blur',
					},
				],
			},
			brand: {
				id: null,
				name: '',
				initial: '',
				logo: '',
				delState: '',
			},
			// request.defaults.baseURL 获取全局通用url前缀
			uploadUrl:
				request.defaults.baseURL + '/api-goods/proBrand/uploadImage',
			dialogVisible: false,
			tableData: [],
			currentPage: null,
			pageNum: 1,
			pageSize: 10,
			pageSizes: [5, 10, 25, 50],
			total: null,
			sortValue: null,
			editTitle: '',
			// checkbox: false,
			multipleSelection: [],
		}
	},
	methods: {
		// 初始化列表
		initData() {
			let pageNum = this.pageNum
			let pageSize = this.pageSize
			this.form.name = ''
			// 排序方式 为null默认 0 编号排序
			// this.sortValue -= 0 // this.sortValue = this.sortValue - 0
			let sort = this.sortValue - 0
			brandApi.pageList(pageNum, pageSize, sort).then((response) => {
				this.tableData = response.data.data.records
				this.total = response.data.data.total
			})
		},
		// 添加品牌 显示对话弹窗界面
		addNewBrand() {
			this.editTitle = '添加品牌'
			this.dialogFormVisible = true
			// 如果this.$refs["brandForm"] 不是undefined 就清除验证状态
			if (this.$refs['brandForm']) {
				// 清除验证状态
				this.$refs['brandForm'].resetFields()
			}
			// 重置表单数据
			this.brand = { id: null, name: '', initial: '', logo: '' }
		},
		// 保存数据
		insertSave() {
			this.dialogFormVisible = false
			// 上传图片
			this.$refs.upload.submit()
		},
		// 根据id 更新品牌
		handleClick(data) {
			// 如果this.$refs["brandForm"] 不是undefined 就清除验证状态
			if (this.$refs['brandForm']) {
				// 清除验证状态
				this.$refs['brandForm'].resetFields()
			}
			this.editTitle = '更新品牌'
			this.dialogFormVisible = true
			this.brand.id = data.id
			this.brand.name = data.name
			this.brand.initial = data.initial
			this.brand.logo = data.logo
			this.brand.delState = data.delState
		},
		updateSave() {
			this.dialogFormVisible = false
			// 上传图片
			this.$refs.upload.submit()
			// await brandApi.updateById(this.brand).then(() => {
			//   this.initData();
			// });
		},
		// 根据id 删除品牌
		deleteClick(id) {
			//下列请求都可调试通过
			// brandApi.deleteById(id);
			// brandApi.deleteById(id).then();
			brandApi.deleteById(id).then(() => {
				if (this.form.name != '') {
					this.selectResults()
				} else {
					this.initData()
				}
			})
		},
		Goods() {
			this.$router.push({ path: '/goods/goodsList' })
		},
		Evaluate() {
			this.$router.push({ path: '/goods/goodsEvaluation' })
		},
		// 数据列表
		toggleSelection() {
			if (this.tableData) {
				this.tableData.forEach((row) => {
					// 全选 或 反选
					// this.$refs.multipleTable.toggleRowSelection(row);
					// 全选 或 全不选
					this.$refs.multipleTable.toggleAllSelection()
				})
			} else {
				this.$refs.multipleTable.clearSelection()
			}
		},
		/* toggleSelectionCheckbox() {
      if (this.checkbox) {
        this.tableData.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    }, */
		// 分页条数更改后操作
		handleSizeChange(val) {
			this.pageSize = val
			this.pageNum = 1
			// 需要 更换显示条数后 跳转第一页时
			// this.pageNum = 1
			if (this.form.name != '') {
				this.selectResults()
			} else {
				this.initData()
			}
		},
		// 当前页更改后操作
		handleCurrentChange(val) {
			this.pageNum = val
			if (this.form.name != '') {
				this.selectResults()
			} else {
				this.initData()
			}
		},
		//选择后操作 this.multipleSelection 对象数组
		handleSelectionChange(val) {
			// 当前面 data() 对象中未定义是 也可执行当前行 当此情况执行当前行时 相当于 在data对象中新定义了个multipleSelection 并进行了赋值
			// 所以在未执行当前行时 multipleSelection 的值为 undefined
			// this.multipleSelection = val;
			// 因为此方法是在选择改变时调用，所以必须初始化数组 如果不初始化数组 数组将会层层叠加
			this.multipleSelection = []
			// 为multipleSelection赋值   multipleSelection为id数组
			val.forEach((v) => {
				this.multipleSelection[this.multipleSelection.length] = v.id
			})
		},
		onSubmit() {
			this.dialogVisible = true
		},
		resetForm(formName) {
			this.$refs[formName].resetFields()
		},
		//生成首字母
		generateInitial() {
			brandApi
				.generateInitial(this.pageNum, this.pageSize)
				.then((response) => {
					this.tableData = response.data.data.records
					this.total = response.data.data.total
				})
		},
		// 上传logo成功操作
		handleChange(file, fileList) {
			// 清除列表
			// this.$refs.upload.clearFiles();
			// 预加载显示图片
			this.brand.logo = URL.createObjectURL(file.raw)
		},
		// 上传logo成功操作
		handleUpload(file) {
			// 加上时间戳 解决浏览器本地图片更新后浏览器读取缓存 无法做到同步更新
			let getTimestamp = new Date().getTime()
			// 拼装url 访问地址
			this.brand.logo =
				request.defaults.baseURL +
				'/api-goods' +
				file.data.url +
				'?timestamp=' +
				getTimestamp
			// this.uploadUrl= "https://jsonplaceholder.typicode.com/posts/";
			if (this.brand.id) {
				brandApi.updateById(this.brand).then(() => {
					this.initData()
				})
			} else {
				brandApi.addBrand(this.brand).then(() => {
					this.initData()
				})
			}
		},
		beforeUpload(file) {
			//限制图片格式 和 <el-upload accept="image/jpeg,image/jpg,image/png" ></el-upload> 作用相同   使用accept限制后 将只能找到符合限制的文件
			const isJPG =
				file.type === 'image/jpg' ||
				file.type === 'image/jpeg' ||
				file.type === 'image/png'
			//限制图片大小
			// const isLt2M = file.size / 1024 / 1024 < 2;
			const isLt500KB = file.size / 1024 < 500

			if (!isJPG) {
				this.$message.error('上传头像图片只能是 JPG 、JPEG、PNG格式!')
			}
			if (!isLt500KB) {
				this.$message.error('上传头像图片大小不能超过 500KB!')
			}
			return isJPG && isLt500KB
			// return isLt500KB;
			// this.uploadUrl=request.defaults.baseURL + "/api-goods/proBrand/uploadImage";
		},
		//批量处理操作
		handleSelection() {
			if (this.multipleSelection.length > 0 && this.form.type != null) {
				brandApi
					.batchOperation(this.multipleSelection, this.form.type)
					.then(() => {
						if (this.form.name != '') {
							this.selectResults()
						} else {
							this.initData()
						}
						// this.checkbox = false;
					})
			}
		},
		// 根据品牌名称查询
		selectResults() {
			// this.pageNum = 1;
			if (this.currentPage != null) {
				this.pageNum = this.currentPage
				this.currentPage = null
			}
			let getData = {
				pageNum: this.pageNum,
				pageSize: this.pageSize,
				sort: this.sortValue - 0,
				matchName: this.form.name,
			}
			brandApi.pageMatch(getData).then((response) => {
				this.tableData = response.data.data.records
				this.total = response.data.data.total
			})
		},
	},
	watch: {
		sortValue() {
			if (this.form.name != '') {
				this.selectResults()
			} else {
				this.initData()
			}
		},
		'form.name': {
			handler: function() {
				this.currentPage = 1
			},
		},
	},
	filters: {
		delStateFilter(type) {
            // 在过滤器中不能引用当前实例
            // const delObj =  delStateType.find((obj) => obj.type === type - 0)
			// return delObj ? delObj.title : null
			return delStateType.find((obj) => obj.type === type - 0).title
		},
	},
	created() {
		this.initData()
	},
}
</script>
<style scoped>
.selection-width {
	width: 110px;
}
.margin-left {
	margin-left: 10px;
}
.footer-style {
	background-color: #fdfdfe;
	height: 60px;
	line-height: 60px;
	position: relative;
}
.footer-style .batch {
	position: absolute;
	left: 10px;
}
.footer-style .pagination {
	position: absolute;
	right: 10px;
	display: inline-block;
	top: 15px;
}
/* .parent-body {
  border: 1px solid #e4e4e4;
} */
.content-header {
	height: 50px;
	line-height: 50px;
	background-color: #f3f3f3;
	color: #666666;
	position: relative;
	text-align: left;
}
/* 
.el-upload-dragger {
  width: 153px;
  height: 40px;
  text-align: center;
}
.el-upload .el-upload--text {
  width: 153px;
  height: 40px;
} */
/* .upload-demo {
  width: 153px;
  height: 40px;
} */
</style>
<style>
.avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px !important;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}
.avatar-uploader .el-upload:hover {
	border-color: #409eff;
}
.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	line-height: 178px;
	text-align: center;
}
.avatar {
	width: 178px;
	height: 178px;
	display: block;
}
</style>
